

import 'dart:async';

import 'package:oral_cloud/config/storage_manager.dart';
import 'package:oral_cloud/provider/view_state_model.dart';
import 'package:oral_cloud/service/oral_repository.dart';
import 'package:oral_cloud/view_model/user_model.dart';

const String kLoginName = 'kLoginName';

class LoginModel extends ViewStateModel{
  static const int LoginTypePwd = 1;
  static const int LoginTypeVCode = 2;
  final UserModel userModel=UserModel();
  LoginModel();


  String getLoginName() {
    return StorageManager.sharedPreferences.getString(kLoginName);
  }

  //username 用户名 一般指手机号
  //newPassword 修改后的密码
  //vCode 验证码
  Future<bool> modifyPassword(String mobile,String newPassword,String vCode) async{
    setBusy();
    try{
      await OralRepository.modifyPassword(mobile, newPassword, vCode);
//      print('modifyPassword result=$result');
//      if(result==null){
//        return false;
//      }
      setIdle();
      return true;
    }
    catch(e,s){
      setError(e, s);
      return false;
    }
  }


  Future<bool> login(String loginName,String pwdOrVCode,int loginType) async{
    setBusy();
    try{
      var user = await OralRepository.login(loginName, pwdOrVCode,loginType);
      if(user==null){
        return false;
      }
      print('login user=$user');
      userModel.saveUser(user);
      StorageManager.sharedPreferences.setString(kLoginName, loginName);
      setIdle();
      return true;
    }
    catch(e,s){
      setError(e, s);
      return false;
    }
  }



  Future <Null> logout() async{
    setBusy();
    userModel.clearUser();
    setIdle();
  }
}

class VCodeModel extends ViewStateModel{
  Future<bool> getVCode(String mobile) async{
    setBusy();
    try{
      bool result=await OralRepository.getVCode(mobile);
      print('result=$result');
      setIdle();
      return result;
    }
    catch(e,s){
      setError(e, s);
      return false;
    }
  }
}